import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.util.HashMap;


public class Console extends JPanel  implements ActionListener {
	
	private JTextArea console; 
	private boolean debutConsole = true;
	private Box box;
	private JTextField consoleExec;
	private JButton consoleExecBouton;
	private Logo logo;
	
	public Console(Logo l){
		super();
		this.logo=l;
		this.setLayout(new BorderLayout());//adapte le JTextArea � la fenetre de la console
		
		console = new JTextArea();
		console.setEditable(false);		
		box = Box.createHorizontalBox();
		consoleExec = new JTextField();
		consoleExecBouton = new JButton("Executer");
		consoleExecBouton.addActionListener(this);
		
		this.add(new JScrollPane(console), BorderLayout.CENTER);
		this.add(box, BorderLayout.SOUTH);
		box.add(consoleExec);
		box.add(consoleExecBouton);		
	}
	
	public void out(String resultat)
	{	
		console.setForeground(Color.GREEN);
		if(debutConsole)
		{console.append(resultat);
		 debutConsole=false;
		}	
		else	
			console.append("\n"+resultat);
	}
	
	public void sys(String resultat)
	{
		console.setForeground(Color.BLUE);
		if(debutConsole)
		{console.append(resultat);
		 debutConsole=false;
		}	
		else

			console.append("\n"+resultat);
	}
	
	public void err(String resultat)
	{
		console.setForeground(Color.RED);
		if(debutConsole)
		{
			console.append(resultat);
			debutConsole=false;
		}	
		else			
			console.append("\n"+resultat);
	}

	public void actionPerformed(ActionEvent e) 
	{		
		ByteArrayInputStream stream  = new ByteArrayInputStream(consoleExec.getText().getBytes());
    	ParserLogo parser = new ParserLogo(stream);
    	parser.initBibliotheque(logo.getBiblio());
    	parser.initEnv(new HashMap<String, Object>());    	
    	try 
    	{
			parser.run();			
		} 
    	catch (ParseException e1) {System.out.println(e1.toString());} 
		catch (Exception e1) {System.out.println(e1.toString());}
	}
}
